package com.org.controller.user;

import com.org.constant.JwtClaimsConstant;
import com.org.dto.UserLoginDTo;
import com.org.entity.User;
import com.org.properties.JwtProperties;
import com.org.result.Result;
import com.org.service.UserService;
import com.org.utils.JwtUtil;
import com.org.vo.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/user/user")
@Api(tags = "C段相关接口")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     * @param userLoginDTo
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVo> login(@RequestBody UserLoginDTo userLoginDTo){
        log.info("微信用户登录:{}", userLoginDTo.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTo);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        //放入用户的主键值
        claims.put(JwtClaimsConstant.USER_ID,user.getUid());
        String token =JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);

        UserLoginVo userLoginVo= UserLoginVo.builder()
                .id(user.getUid())
                .openid(user.getOpenid())
                .token(token).build();
        return Result.success(userLoginVo);
    }
}
